#include "showfiche.h"
#include "constants.h"
#include "tools.h"
#include <qprintereasy.h>
#include <QTextDocumentFragment>
#include <QDebug>
#include <QMessageBox>

using namespace Constants;
using namespace ToolsSpace;

ShowResultsFile::ShowResultsFile(QWidget * parent)
{
    Q_UNUSED(parent);
    setupUi(this);
    Tools t(this);
    m_resourcespath = t.pathToResources();
    m_textDocument = new QTextDocument(this);
    m_exportPath = QDir::homePath();
    QFile file(m_resourcespath+"/outputstockfile");
    if (!file.open(QIODevice::ReadOnly))
    {
        qWarning() << __FILE__ << QString::number(__LINE__) << "unable to open file : " << qApp->applicationDirPath()+"/../resources/outputstockfile";
        }
    QTextStream stream(&file);
    while (!stream.atEnd())
    {
        m_exportPath = stream.readLine();
        }
    exportPathEdit->setText(m_exportPath);
    connect(eraseButton,SIGNAL(pressed()),this,SLOT(eraseFragment()));
    connect(printButton,SIGNAL(pressed()),this,SLOT(printDatas()));
    connect(exportToPdfButton,SIGNAL(pressed()),this,SLOT(printToPdfFile()));
}

ShowResultsFile::~ShowResultsFile(){}

void ShowResultsFile::setInformations(const QHash<int,QString> & hashOfDatas)
{
    QString fichedatas;
    QTextDocument *terraindoc = new QTextDocument(this);
    QTextDocument *documentsdoc = new QTextDocument(this); 
    QTextDocument *ordonnancesdoc = new QTextDocument(this);
    QTextDocument *observationdoc = new QTextDocument(this);   
    QTextCursor cursor(m_textDocument);
    int terrainsize= 0,docsize= 0,ordosize= 0,observsize = 0;
    QHashIterator<int,QString> it(hashOfDatas);
    while (it.hasNext())
    {
        it.next();
        int type = it.key();
        fichedatas = it.value();
        //qDebug() << __FILE__ << QString::number(__LINE__) << " fichedatas =" << fichedatas ;
        switch(type){
            case TERRAIN :
                terraindoc->setPlainText(fichedatas);
                terrainsize = fichedatas.size();
                break;
            case DOCUMENTS :
                documentsdoc->setHtml(fichedatas);
                docsize = fichedatas.size();
                break;
            case ORDONNANCE_AJUSTABLE :
                ordonnancesdoc->setHtml(fichedatas);
                ordosize = fichedatas.size();
                break;
            case OBSERVATION :
                observationdoc->setHtml(fichedatas);
                observsize = fichedatas.size();
                break;
            default :
                break;    
            }            
        }  
    QTextDocumentFragment terrainfragment(terraindoc);
    QTextDocumentFragment documentsfragment(documentsdoc);
    QTextDocumentFragment ordonnancesfragment(ordonnancesdoc);
    QTextDocumentFragment observationfragment(observationdoc);
    //qDebug() << __FILE__ << QString::number(__LINE__) << " texte  =" << terrainfragment.toPlainText() ;
    cursor.setPosition(0); 
    cursor.insertFragment(terrainfragment);
    cursor.movePosition(QTextCursor::End);
    cursor.insertFragment(documentsfragment);
    cursor.movePosition(QTextCursor::End);
    cursor.insertFragment(ordonnancesfragment);
    cursor.movePosition(QTextCursor::End);
    cursor.insertFragment(observationfragment);
    textEdit->setDocument(m_textDocument);
}

void ShowResultsFile::printDatas()
{
    QDateTime datetime = QDateTime::currentDateTime();
    QString datetimestr = datetime.toString(Qt::ISODate);
    QString outputfile;
    QString outputDir = exportPathEdit->text();
    QDir dir(outputDir);
    if(!dir.exists())
    {
        //dir.mkpath(outputDir);
        dir.mkdir(outputDir);
        }
    QString resources_memoryfile= m_resourcespath+"/outputstockfile";
    QFile outputmemoryfile(resources_memoryfile);
    if (!outputmemoryfile.open(QIODevice::ReadWrite|QIODevice::Truncate))
    {
        qWarning() << __FILE__ << QString::number(__LINE__) << "unable to open : "+resources_memoryfile ;
        }
    QTextStream stream(&outputmemoryfile);
    while (!stream.atEnd())
    {
        outputDir = stream.readLine();
        }
    if (!outputDir.endsWith("/"))
    {
        outputDir += "/";
        }
    outputfile = outputDir+"dossier_"+m_name+"_"+m_firstname+"_"+m_patientguid+"_"+datetimestr+".pdf";
    stream << exportPathEdit->text();
    QString textHtml = textEdit->toHtml();
    QPrinterEasy pe;
          pe.askForPrinter();
          pe.printer()->setOutputFileName(outputfile);
          pe.setHeader( "" );
          pe.setFooter( "" );
          pe.setContent( textHtml );
          if (pe.previewDialogTest()== QDialog::Accepted)
          {
              qDebug() << __FILE__ << QString::number(__LINE__) << "printed" ;
              }
}

void ShowResultsFile::printToPdfFile()
{
    QDateTime datetime = QDateTime::currentDateTime();
    QString datetimestr = datetime.toString(Qt::ISODate);
    QString outputfile;
    QString outputDir = exportPathEdit->text();
    QDir dir(outputDir);
    if(!dir.exists())
    {
        //dir.mkpath(outputDir);
        dir.mkdir(outputDir);
        }
    QString resources_memoryfile= m_resourcespath+"/outputstockfile";
    QFile outputmemoryfile(resources_memoryfile);
    if (!outputmemoryfile.open(QIODevice::ReadWrite|QIODevice::Truncate))
    {
        qWarning() << __FILE__ << QString::number(__LINE__) << "unable to open : "+resources_memoryfile ;
        }
    QTextStream stream(&outputmemoryfile);
    while (!stream.atEnd())
    {
        outputDir = stream.readLine();
        }
    if (!outputDir.endsWith("/"))
    {
        outputDir += "/";
        }
    //outputfile = outputDir+"dossier_"+m_name+"_"+m_firstname+"_"+m_patientguid+"_"+datetimestr+".pdf";
    outputfile = outputDir+"dossier_"+m_name+"_"+m_firstname+"_"+m_patientguid+".pdf";
    stream << exportPathEdit->text();
    QString textHtml = textEdit->toHtml();
    QPrinter * printer = new QPrinter;
    QPrinterEasy pe;
    pe.setContent( textHtml);
    pe.setPrinter(printer);
    if (pe.toPdf(outputfile,textHtml))
    {
        QMessageBox::information(0,tr("Ok"),tr("Le dossier est ici : ")+outputfile,QMessageBox::Ok);
        }
    else{
        QMessageBox::warning(0,tr("Erreur"),tr("Le dossier n'est pas sorti."),QMessageBox::Ok);
    }
}

void ShowResultsFile::getNameAndGuid(const QString name, const QString firstname, const QString patientguid)
{
    m_name = name;
    m_firstname = firstname;
    m_patientguid = patientguid;
}

void ShowResultsFile::eraseFragment()
{
    //TODO
}
